package test.src.网络编程;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.PrintWriter;
import java.net.Socket;

public class MyClient{
    JFrame jFrame;
    private PrintWriter writer;
    Socket socket;
    private JTextArea ta = new JTextArea();
    private JTextField tf = new JTextField();
    JPanel jPanel = new JPanel();

    public void init(String title) {
        jFrame = new JFrame(title);
        final JScrollPane scrollPane = new JScrollPane(ta);
        scrollPane.setBorder(new BevelBorder(BevelBorder.RAISED));
//        scrollPane.setViewportView(ta);
        jPanel.setLayout(new BorderLayout());
        jPanel.add(scrollPane);
        jPanel.add(tf,BorderLayout.SOUTH);
        jFrame.add(jPanel);
        jFrame.setBounds(0, 0 ,400, 400);
        tf.addActionListener((ActionEvent e) -> {
            //将文本框中的信息写入流
            writer.println(tf.getText());
            //将文本框中的信息显示在文本域中
            ta.append(tf.getText() + "\n");
            ta.setSelectionEnd(ta.getText().length());
            tf.setText("");
        });
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    private void connect() {
        //尝试连接
        try {
            socket = new Socket("10.69.49.253", 8998);
            writer = new PrintWriter(socket.getOutputStream(), true);
            ta.append("完成连接" + "\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyClient client = new MyClient();
        client.init("向服务器发生数据");
        client.connect();
    }
}
